package cn.touna.jss.modules.third.baihang.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class RequestRunnable  {


    public String  run() {
        //指定通讯协议，demo中可选择http和https。建议使用https。
        String type = "https";  

        //企业ID，由对接窗口人员提供
        String secretId = "TTNW0003";
        //企业密钥，由对接窗口人员提供
        String secretKey = "GbUgAd/saJIxOzcfXmgWzXlu3IxUFQvj";
        
        //企业查询请求流水号，不可以重复。此处样例为时间戳方式生成，实际生成规则可以自定义。

        //服务接口地址，调用前请确认网络连通性
        //testmock为测试挡板，实际查询请将teskmock修改为实际数据产品ID
//        String restURL = "https://14.21.41.141:10443/queryData/testmock";
        String restURL = "https://14.21.41.141:10443/queryData/MBASU001";

				//组装请求参数map -- 此处仅为模拟测试数据，实际测试请参考对应数据产品要求
        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("mobile","13012345678");
        paraMap.put("certType","01");
        paraMap.put("certNo","210381197509111316");
        paraMap.put("name","张三");        String requestRefId = "DEMOREQ_" + new SimpleDateFormat("yyMMddHHmmssSSS").format(new Date()) + (int)((Math.random()*9+1)*100000);



        ReportService reportService = new ReportService();
        try {
            RequestParameter requestParameter = new RequestParameter();
            String beforeSign = "requestRefId=" + requestRefId + "&secretId=" + secretId;

						//生成签名
            byte[] keyBytes= new BASE64Decoder().decodeBuffer(secretKey);
            SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(beforeSign.getBytes());
            String signature = new BASE64Encoder().encode(rawHmac);

						//组装请求
            RequestParameter.Head head =  requestParameter.new Head(requestRefId,secretId,signature);
            RequestParameter.Request request = requestParameter.new Request(paraMap);
            requestParameter.setSecretKey(secretKey);
            requestParameter.setHead(head);
            requestParameter.setRequest(request);
            
            String rawString = reportService.makePostCall(requestParameter, restURL, type);
            
            //打印原始数据
            System.out.println(rawString);
            String responseStr = rawString.split("\"response\":\"")[1].split("\"")[0];
            String data = reportService.decryptResponse(responseStr, "3des", secretKey);
            //打印解密后的response内容
            System.out.println("data: " + data);

            return data;
        } catch (Exception e) {
        		e.printStackTrace();
        }
        return "";
    }

    private int getNow(){
        return Integer.parseInt(new SimpleDateFormat("hhmmssSSS").format(new Date()));
    }
}
